package com.yuejian_06.yuejian_06.activity;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.yuejian_06.yuejian_06.Listener.MeListener;
import com.yuejian_06.yuejian_06.R;
import com.yuejian_06.yuejian_06.bean.SuccessBean;
import com.yuejian_06.yuejian_06.bean.UserInfoBean;
import com.yuejian_06.yuejian_06.fragment.Constants;
import com.yuejian_06.yuejian_06.fragment.PicFragment;
import com.yuejian_06.yuejian_06.model.PicModel;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PostPicActivity extends BaseActivity {
    private EditText ed_picmian;
    private TextView contentSize;
    private Button postpic;
    private ImageButton takepic,back;
    private ImageView picphoto;


    private final String TAG = "PostPicActivity";

    private Resources res;
    private String photoName = Constants.deaultHeadPhotoName;

    private File mCurrentPhotoFile;// 照相机拍照得到的图片
    // 用来标识请求照相功能的activity
    private static final int CAMERA_WITH_DATA = 3023;

    // 用来标识请求gallery的activity
    private static final int PHOTO_PICKED_WITH_DATA = 3021;

    // 拍照的照片存储位置
    private static final File PHOTO_DIR = new File(
            Environment.getExternalStorageDirectory() + "/DCIM/Camera");
    private byte[] img; // 头像数据

    @Override
    void initViews() {

    }
    @Override
    void initEvents() {

    }
    @Override
    void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post_pic);
        initView();
        initEvent();
    }

    private void initView(){
        ed_picmian = (EditText) findViewById(R.id.ed_picmain);
        contentSize = (TextView) findViewById(R.id.contentSize);
        postpic = (Button) findViewById(R.id.postpic);
        picphoto = (ImageView) findViewById(R.id.picphoto);
        takepic = (ImageButton) findViewById(R.id.takepic);
        back = (ImageButton) findViewById(R.id.back);
        takepic.setOnClickListener(new ChangePhotoListener());
    }

    private void initEvent(){
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //处理还有多少文字可以输入
        ed_picmian.addTextChangedListener(new TextWatcher() {
            private CharSequence temp;
            @Override
            public void onTextChanged(CharSequence s, int start, int before,int count) {
                // TODO Auto-generated method stub
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,int after) {
                // TODO Auto-generated method stub
                temp = s;
            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                int size = 150 - temp.length();
                contentSize.setText(size + "");
            }
        });

        //处理发表晒图
        postpic.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                String pic_main = ed_picmian.getText().toString();
                PicModel picModel = new PicModel();
                picModel.getPostPic(getUser_id(),pic_main,meListener);
                finish();
            }
        });
    }

    private MeListener<SuccessBean> meListener =new MeListener<SuccessBean>() {
        @Override
        public void onResponse(SuccessBean o) {
            Toast.makeText(PostPicActivity.this,"发表晒图成功",Toast.LENGTH_SHORT).show();
        }
        @Override
        public void onFail(String msg) {
            Toast.makeText(PostPicActivity.this,"发表晒图失败",Toast.LENGTH_SHORT).show();
        }
    };




    // 弹出提示信息
    public void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    private class ChangePhotoListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Context context = PostPicActivity.this;
            final Context dialogContext = new ContextThemeWrapper(context,
                    android.R.style.Theme_Light);
            String cancel = "返回";
            String[] choices;
            choices = new String[2];
            choices[0] = getString(R.string.take_photo);
            choices[1] = getString(R.string.pick_photo);
            final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
                    android.R.layout.simple_list_item_1, choices);

            final AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext);
            builder.setTitle(R.string.attachToContact);
            builder.setSingleChoiceItems(adapter, -1,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            switch (which) {
                                case 0: {
                                    String status = Environment
                                            .getExternalStorageState();
                                    if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
                                        doTakePhoto();// 用户点击了从照相机获取
                                    } else {
                                        showToast("没有SD卡");
                                    }
                                    break;

                                }
                                case 1:
                                    doPickPhotoFromGallery();// 从相册中去获取
                                    break;
                            }
                        }
                    });
            builder.setNegativeButton(cancel,
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }

                    });
            builder.create().show();
        }
    }



    // 因为调用了Camera和Gallery所以要判断他们各自的返回情况,它们启动时是使用startActivityForResult()方法
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK)
            return;
        switch (requestCode) {
            case PHOTO_PICKED_WITH_DATA: {// 调用Gallery返回的
                final Bitmap photo = data.getParcelableExtra("data");
                // 下面就是显示照片了
                System.out.println(photo);
                // 缓存用户选择的图片
                img = getBitmapByte(photo);
                Log.v("PostPicActivity", "new photo set!");
                // mEditor.setPhotoBitmap(photo);
                picphoto.setImageBitmap(photo);
                System.out.println("set new photo");
                photoName = getPhotoFileName();
                break;
            }
            case CAMERA_WITH_DATA: {// 照相机程序返回的,再次调用图片剪辑程序去修剪图片
                doCropPhoto(mCurrentPhotoFile);
                break;
            }
        }
    }

    /**
     * 拍照获取图片
     *
     */
    protected void doTakePhoto() {
        try {
            // Launch camera to take photo for selected contact
            PHOTO_DIR.mkdirs();// 创建照片的存储目录
            mCurrentPhotoFile = new File(PHOTO_DIR, getPhotoFileName());// 给新照的照片文件命名
            final Intent intent = getTakePickIntent(mCurrentPhotoFile);
            startActivityForResult(intent, CAMERA_WITH_DATA);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(this, R.string.photoPickerNotFoundText,
                    Toast.LENGTH_LONG).show();
        }
    }

    public static Intent getTakePickIntent(File f) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
        return intent;
    }

    /**
     * 用当前时间给取得的图片命名
     *
     */
    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
        return dateFormat.format(date) + ".png";
    }

    // 请求Gallery程序
    protected void doPickPhotoFromGallery() {
        try {
            // Launch picker to choose photo for selected contact
            final Intent intent = getPhotoPickIntent();
            startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(this, R.string.photoPickerNotFoundText1,
                    Toast.LENGTH_LONG).show();
        }
    }

    // 封装请求Gallery的intent
    public static Intent getPhotoPickIntent() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
        intent.setType("image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 80);
        intent.putExtra("outputY", 80);
        intent.putExtra("return-data", true);
        return intent;
    }



    // 将字节数组转换为bitmap
    public Bitmap getBitmapFromByte(byte[] temp) {
        if (temp != null) {
            Bitmap bitmap = BitmapFactory.decodeByteArray(temp, 0, temp.length);
            return bitmap;
        } else {
            return null;
        }
    }

    // 将头像转换成byte[]以便能将图片上传到服务器
    public byte[] getBitmapByte(Bitmap bitmap) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
        return out.toByteArray();
    }

    protected void doCropPhoto(File f) {
        try {
            final Intent intent = getCropImageIntent(Uri.fromFile(f));
            startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
        } catch (Exception e) {
            Toast.makeText(this, R.string.photoPickerNotFoundText,
                    Toast.LENGTH_LONG).show();
        }
    }

    /**
     * Constructs an intent for image cropping. 调用图片剪辑程序
     */
    public static Intent getCropImageIntent(Uri photoUri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(photoUri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 80);
        intent.putExtra("outputY", 80);
        intent.putExtra("return-data", true);
        return intent;
    }








            //上传图片
//            if (photoName != null && !photoName.equals(Constants.deaultHeadPhotoName)) {
//                call = regService.uploadImage(photoName
//                        , Base64.encodeBytes(img));
//                call.enqueue(new Callback<String>() {
//
//                    @Override
//                    public void onFailure(Call<String> arg0, Throwable arg1) {
//                        // TODO Auto-generated method stub
//
//                    }
//
//                    @Override
//                    public void onResponse(Call<String> arg0,
//                                           Response<String> arg1) {
//                        // TODO Auto-generated method stub
//                        String result = arg1.body();
//                        if (!"success".equals(result.trim())) {
//                            showToast("头像上传失败，将使用系统默认头像");
//                            photoName = Constants.deaultHeadPhotoName;
//                        }
//                        else{
//                            showToast("头像上传成功");
//                        }
//
//                    }
//                });
//
//            } else if (photoName == null) {
//                photoName = Constants.deaultHeadPhotoName;
//            }


}
